package tech.aistar.controller;

import tech.aistar.pojo.User;
import tech.aistar.service.IUserService;
import tech.aistar.service.impl.UserServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;

/**
 * 本类用来演示: 用户的控制层 - 负责接收视图传过来的参数,然后调用service层
 *                          负责进行跳转....
 *
 * @author: success
 * @date: 2021/4/16 8:39 上午
 */
@WebServlet(urlPatterns = "/user/*")
public class UserController extends HttpServlet {

    private IUserService userService = new UserServiceImpl();

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String pathInfo = req.getPathInfo();
        switch (pathInfo){
            case "/login":
                //处理post请求中文乱码问题
                req.setCharacterEncoding("utf-8");

                //接收参数 - 根据key获取参数值
                //key就是对应表单控件中的name属性的值 - username,password
                String username = req.getParameter("username");

                String password = req.getParameter("password");
                //controller层调用service层..
                User user = userService.login(username);
                //判断...
                if(null != user){
                    //进行密码的判断
                    if(user.getPassword().equals(password)){
                        //记住密码...
                        String isForget = req.getParameter("isForget");
                        //如果被勾选了,那么就为on
                        if("on".equals(isForget)){
                            //记住密码...
                            //二级编码.
                            username = URLEncoder.encode(URLEncoder.encode(username,"utf-8"),"utf-8");
                            //创建cookie对象
                            Cookie c = new Cookie("loginInfo",username+":"+user.getPassword());
                            c.setPath("/");
                            c.setMaxAge(60*10);//10分钟
                            //将这个cookie发送到client
                            resp.addCookie(c);
                        }else{
                            Cookie c = new Cookie("loginInfo","");
                            c.setPath("/");
                            c.setMaxAge(60*10);//10分钟
                            //将这个cookie发送到client
                            resp.addCookie(c);
                        }
                        resp.sendRedirect("/aistar/hello.jsp");

                    }else{
                        //密码是错误的...
                        resp.sendRedirect("/aistar/user/loginView?error=1");
                    }

                }else{
                    //用户不存在...
                    resp.sendRedirect("/aistar/user/loginView?error=0");
                }
                break;
        }
    }
}
